package com.hyl.accountbook;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

import com.hyl.dao.DBOpenHelper;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class TwoFragment extends Fragment {


    private static final int[] COLORS = {Color.BLUE, Color.GREEN, Color.MAGENTA, Color.RED};
    private Integer sumVal = 0;

    private LinearLayout ll_expense_piechart;
    private GraphicalView graphicalView;

    public TwoFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_two, container, false);

        initPieChart(v);

        return v;
    }

    /**
     * 生成饼图
     */
    private void initPieChart(View v){
        //先判断用户是否登录
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("setting", Activity.MODE_PRIVATE);
        String userID =sharedPreferences.getString("userID", "");
//        String userID ="17866626439";
        Log.i("info", "此次登录的用户是" + userID);
        if(userID.isEmpty()){
            new AlertDialog.Builder(getActivity())
                    .setTitle("提示")
                    .setMessage("您还未登录，请点击确定按钮进行登录！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            Intent intent=new Intent(getActivity(),LoginActivity.class);
                            getActivity().startActivity(intent);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            return;
                        }
                    })
                    .show();
        }else {    //call DBOpenHelper
            //因为它使用的是Android的默认数据库 这里是新建数据库连接
            DBOpenHelper helper = new DBOpenHelper(getActivity(),"qianbao.db",null,1);
            SQLiteDatabase db = helper.getWritableDatabase();
            //这里是进行数据库查询(返回的应该是多条数据)
            Cursor c = db.query("basicCode_tb",null,"userID=?",new String[]{userID},null,null,null);
            c.moveToFirst();
            //这个iColCount 就是有多少条数据
            int iColCount = c.getColumnCount();
            int iNumber = 0; //图表系列数
            List<Integer> dataList = new ArrayList<>();

            //这个循环是处理每一条数据
            while (iNumber < c.getCount()){
                int a=c.getColumnIndex("cost");

                Integer value=Integer.parseInt(c.getString(a));

                dataList.add(value);
                sumVal += value;
                c.moveToNext();
                iNumber++;
            }

            //处理完了关闭数据库
            c.close();
            db.close();

            CategorySeries dataset = buildCategoryDataset("图文报表",dataList);
            DefaultRenderer renderer = buildCategoryRenderer(iNumber);

            ll_expense_piechart = (LinearLayout) v.findViewById(R.id.ll_expense_piechart);
            ll_expense_piechart.removeAllViews();

            graphicalView = ChartFactory.getPieChartView(getContext()
                    ,dataset, renderer);//饼状图
            graphicalView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

            ll_expense_piechart.addView(graphicalView);
        }


    }

    /**
     * 构建数据集
     * @param title
     * @param dataList
     * @return
     */
    protected CategorySeries buildCategoryDataset(String title, List<Integer> dataList){
        CategorySeries series =new CategorySeries(title);

        for (Integer value : dataList){

            series.add(String.valueOf(value), (double) ((float)value/this.sumVal));
        }

        return series;
    }

    /**
     * 构建渲染器
     * @param num
     * @return
     */
    protected DefaultRenderer buildCategoryRenderer(int num){

        DefaultRenderer renderer = new DefaultRenderer();
        renderer.setLegendTextSize(35);//设置左下角标注文字的大小
        renderer.setLabelsTextSize(25);//饼图上标记文字的字体大小
        renderer.setLabelsColor(Color.BLACK);//饼图上标记文字的颜色
        renderer.setPanEnabled(false);
        //renderer.setDisplayValues(true);//显示数据


        for(int i=0;i<num;i++){
            SimpleSeriesRenderer r = new SimpleSeriesRenderer();
            r.setColor(COLORS[i%4]);
            //设置百分比
            //r.setChartValuesFormat(NumberFormat.getPercentInstance());
            renderer.addSeriesRenderer(r);
        }
        return renderer;
    }
}

